package com.muyu.auth.utils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class SmsService {
 
    @Value("${aliyun.sms.accesskeyid}")
    private String accessKeyId;
 
    @Value("${aliyun.sms.accesskeysecret}")
    private String accessKeySecret;
 
    @Value("${aliyun.sms.signname}")
    private String signName;
 
    @Value("${aliyun.sms.templatecode}")
    private String templateCode;
 
    @Value("${aliyun.sms.regionid}")
    private String regionId;
 
    public SendSmsResponse sendSms(String phoneNumber, String code) throws ClientException {
        // 初始化客户端
        IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint(regionId, regionId, "Dysmsapi", "dysmsapi.aliyuncs.com");
        IAcsClient client = new DefaultAcsClient(profile);
 
        // 构建请求
        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(phoneNumber);       // 目标手机号（多个用逗号分隔）
        request.setSignName(signName);              // 短信签名
        request.setTemplateCode(templateCode);     // 短信模板CODE
        request.setTemplateParam("{\"code\":\"" + code + "\"}"); // 模板参数（JSON格式）
 
        // 发送请求
        return client.getAcsResponse(request);
    }
}
